import datetime
import io
import urllib.parse
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt
from myapp.models import UserInput, UserInput_history
from django.http import JsonResponse
from rest_framework.views import APIView
from django.http import HttpResponse
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet


class pdf(APIView):
    @xframe_options_exempt
    def get(self, request):
        response = HttpResponse(content_type='application/pdf')
        # 获取当前时间
        current_time = datetime.datetime.now()
        # 将时间格式化为精确到秒的字符串
        formatted_time = current_time.strftime("%Y-%m-%d_%H:%M:%S")
        filename = '系统运维知识库_' + formatted_time + '.pdf'
        filename_bytes = filename.encode('utf-8')
        encoded_filename = urllib.parse.quote(filename_bytes)
        response['Content-Disposition'] = f'inline; filename={encoded_filename}'
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=letter, author="Your Name", title="系统运维知识库预览文件")
        data = UserInput.objects.values('type', 'problem', 'Similarity_problem', 'answer')
        data = list(data)
        sorted_data = sorted(data, key=self.custom_sort)
        elements = []
        styles = getSampleStyleSheet()
        # max_lines_per_page = len(sorted_data)
        current_line = 0
        pdfmetrics.registerFont(TTFont('simsun', 'D:\Tencent_IM_8_zby\myproject\myapp\SourceHanSerifCN-Regular.ttf'))
        type = ''
        for item in sorted_data:
            # if current_line >= max_lines_per_page:
            #     elements.append(PageBreak())  # Add a page break
                # doc.build(elements)  # 创建新页面
                # elements = []  # 重置元素列表
                # current_line = 0
            problem = item['problem']
            answer = item['answer']
            # 创建自定义样式以控制文本布局
            custom_style = styles['Normal'].clone(None)
            custom_style.fontName = 'simsun'
            custom_style.wordWrap = 'CJK'
            custom_style.leading = 20  # 设置行高等于字体大小
            if type != item['type']:
                # 设置字体大小
                type = item['type']
                custom_style.fontSize = 25
                elements.append(Paragraph(type, custom_style))
                elements.append(Spacer(1, 20))  # Add some space between sections
            if item['Similarity_problem'] is not None:
                Similarity_problem = item['Similarity_problem']
                # 使用 split() 方法分割文本
                text_list = Similarity_problem.split("/")
                # 设置字体大小
                custom_style.fontSize = 15
                elements.append(Paragraph(problem, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 10
                elements.append(Paragraph(answer, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
                # 设置字体大小
                for i in text_list:
                    custom_style.fontSize = 15
                    elements.append(Paragraph(i, custom_style))
                    elements.append(Spacer(1, 3))  # Add some space between sections
                    # 设置字体大小
                    custom_style.fontSize = 10
                    elements.append(Paragraph(answer, custom_style))
                    elements.append(Spacer(1, 3))  # Add some space between sections
            else:
                # 设置字体大小
                custom_style.fontSize = 15
                elements.append(Paragraph(problem, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 10
                elements.append(Paragraph(answer, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
            current_line += 1
        doc.build(elements)  # 最后一页可能不满，这里再次构建以确保保存
        pdf = buffer.getvalue()
        buffer.close()
        response.write(pdf)
        return response

    # 自定义排序函数，按照type字段排序
    def custom_sort(self, item):
        return item['type']

class question(APIView):
    @csrf_exempt
    def post(self, request, *args, **kwargs):
        dbdata = UserInput.objects.values('problem')
        dbdata = list(dbdata)
        problem = request.data.get('problem')
        if {'problem': problem} in dbdata:
            return JsonResponse({'message':'该问题已存在'})
        type = request.data.get('type')
        Similarity_problem = request.data.get('Similarity_problem')
        answer = request.data.get('answer')
        if Similarity_problem != '':
            Modify_field = '类型，问题，相似问题，答案'
        else:
            Modify_field = '类型，问题，答案'
        data = {
            'movement': "新添",
            "Modify_field": Modify_field
        }
        data1 = {
            'type': type,
            'problem': problem,
            'Similarity_problem': Similarity_problem,
            "answer": answer
        }
        UserInput_history.objects.create(**data)
        UserInput.objects.create(**data1)
        return JsonResponse({'message': '添加成功'})

    @csrf_exempt
    def get(self, request, *args, **kwargs):
        pagenum = int(request.query_params.get('pagenum')) - 1
        # print(type(pagenum))
        pagesize = int(request.query_params.get('pagesize'))
        query = request.query_params.get('query')
        data = UserInput.objects.values('id', 'type', 'problem', 'Similarity_problem', 'answer', 'time')
        data = list(data)
        # 使用sorted函数排序
        sorted_data = sorted(data, key=self.custom_sort)
        le = len(data)
        if query != "":
            sorted_data = [user for user in sorted_data if query in user['problem']]#按照前端模糊查找信息时返回的列表
            le = len(sorted_data)
        user = [sorted_data[i:i + pagesize] for i in range(0, len(sorted_data), pagesize)]
        if user == []:
            data1 = {
                "total": len(data),
                'message': '没有这个问题的相关信息！'
            }
            return JsonResponse(data1,status=201)
        data1 = {
            "results": user[pagenum],
            "total": le,
            # 'message': "查询成功"
        }
        return JsonResponse(data1, safe=False, status=200)

    # 自定义排序函数，按照type字段排序
    def custom_sort(self, item):
        return item['type']

class type_select(APIView):
    @csrf_exempt
    def get(self, request, *args, **kwargs):
        data = UserInput.objects.values('type')
        data = list(data)
        # 使用集合来去重，先将字典转换为元组
        unique_data = [dict(t) for t in {tuple(d.items()) for d in data}]

        # 如果需要再次转回字典列表，可以使用以下方式
        unique_data_as_dicts = [dict(t) for t in unique_data]

        # 使用列表推导式将所有键 "type" 更改为 "value"
        updated_data = [{'value': d['type']} for d in unique_data_as_dicts]

        return JsonResponse(updated_data, safe=False, status=200)

class Data_manipulation(APIView):
    @csrf_exempt
    def get(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        data = UserInput.objects.get(id=id)
        # 将模型实例转换为字典
        user_input_data = {
            'id': data.id,
            'type': data.type,
            'problem': data.problem,
            'Similarity_problem': data.Similarity_problem,
            'answer': data.answer,
        }
        return JsonResponse(user_input_data, safe=False, status=200)

    @csrf_exempt
    def post(self, request, *args, **kwargs):
        id = request.data.get('id')
        data = UserInput.objects.get(id=id)
        type = request.data.get('type')
        problem = request.data.get('problem')
        Similarity_problem = request.data.get('Similarity_problem')
        answer = request.data.get('answer')
        Modify_field = ''
        if type != data.type:
            Modify_field += '类型，'
        if problem != data.problem:
            Modify_field += '问题，'
        if Similarity_problem != data.Similarity_problem:
            Modify_field += '相似问题，'
        if answer != data.answer:
            Modify_field += '答案，'
        if Modify_field != '':
            data = {
                'movement': "修改",
                "Modify_field": Modify_field
            }
            UserInput_history.objects.create(**data)
        data1 = {
            'type': type,
            'problem': problem,
            "Similarity_problem": Similarity_problem,
            "answer":answer
        }
        # print(data1)
        UserInput.objects.filter(id=id).update(**data1)
        return JsonResponse({}, safe=False, status=200)

    @csrf_exempt
    def delete(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        UserInput.objects.filter(id=id).delete()
        data = {
            'movement': "删除",
            "Modify_field": '类型，问题，相似问题，答案'
        }
        UserInput_history.objects.create(**data)
        return JsonResponse({}, safe=False, status=200)

class history(APIView):

    @csrf_exempt
    def get(self, request, *args, **kwargs):
        pagenum = int(request.query_params.get('pagenum')) - 1
        # print(type(pagenum))
        pagesize = int(request.query_params.get('pagesize'))
        # query = request.query_params.get('query')
        data = UserInput_history.objects.values('id', 'movement', 'Modify_field', 'time')
        data = list(data)
        le = len(data)
        # if query != "":
        #     sorted_data = [user for user in data if query in user['problem']]#按照前端模糊查找信息时返回的列表
        #     le = len(sorted_data)
        user = [data[i:i + pagesize] for i in range(0, len(data), pagesize)]
        # if user == []:
        #     data1 = {
        #         "total": len(data),
        #         'message': '没有这个问题的相关信息！'
        #     }
        #     return JsonResponse(data1,status=201)
        data1 = {
            "results": user[pagenum],
            "total": le,
            # 'message': "查询成功"
        }
        return JsonResponse(data1, safe=False, status=200)
